<script setup lang="ts">
// 抽屉
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artAddService, artGetDetailService, artEditService } from '@/apis/article/index'
import { baseURL } from '@/utils/request'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const visibleDrawer = ref(false) //控制抽屉显示隐藏
//组件对外暴漏方法 open 基于open传来的参数去区分添加还是编辑
// open({}) => 表单无需渲染 说明是添加
// open({id:1,cate_name,...}) => 表单需要渲染 说明是编辑
// open调用后可以去打开弹窗
//默认数据
const defaultForm = {
  title: '', //标题
  cate_id: '', //分类id
  cover_img: '', //封面图片 file对象
  content: '', //内容 string
  state: '' //状态
}
// 准备数据
const formModel = ref<any>({ ...defaultForm })

//图片上传逻辑
const imgUrl = ref('')
const onSelectFile = (uploadFile: any) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw) //预览图片
  // 将图片存入formModel.value.cover_img用来提交
  formModel.value.cover_img = uploadFile.raw
}
// 提交
const emit = defineEmits(['success'])
const onPublish = async (state: any) => {
  // 将已发布还是草稿状态 无论是哪一个都存入我们当前的formModel
  formModel.value.state = state
  // 当前接口需要的是formdata 将对象转换成formdata对象 上面的是js的普通对象
  const fd: any = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  // 发请求
  if (formModel.value.id) {
    //编辑操作
    await artEditService(fd)
    ElMessage.success('修改成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    // 添加操作
    await artAddService(fd)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    //通知到我们的父组件添加成功了
    emit('success', 'add')
  }
}
const editorRef = ref<any>(null)
const open = async (row: any) => {
  visibleDrawer.value = true //显示抽屉
  if (row.id) {
    //需要基于row.id发送请求获取编辑对应的详情数据进行回显
    const res = await artGetDetailService(row.id)
    formModel.value = res.data.data
    //图片需要单独处理
    imgUrl.value = baseURL + formModel.value.cover_img
    // 提交给后台需要的数据格式是file对象格式 需要将网络图片地址转换成file对象存储起来
    const file = await imageUrlToFileObject(imgUrl.value, formModel.value.cover_img)
    formModel.value.cover_img = file
  } else {
    formModel.value = { ...defaultForm } //基于默认的数据重置form数据
    // 这里重置了表单的数据 但是图片上传img地址 富文本编辑器内容需要手动重置
    imgUrl.value = ''
    if (editorRef.value) {
      // 添加判断逻辑
      editorRef.value.setHTML('')
    }
  }
}
async function imageUrlToFileObject(imagerUrl: any, filename: any) {
  try {
    //使用Axios下载图片数据
    const response = await axios.get(imagerUrl, { responseType: 'arraybuffer' })

    // 将下载的图片转换成Blob对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type']
    })

    // 创建File对象
    const file = new File([blob], filename, {
      type: response.headers['content-type']
    })
    return file
  } catch (error) {
    console.error('Error converting image URL to File object:', error)
    return null
  }
}
defineExpose({ open })
</script>
<template>
  <el-drawer v-model="visibleDrawer" :title="formModel.id ? '编辑文章' : '添加文章'" direction="rtl" size="50%">
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select v-model="formModel.cate_id" width="100%"></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 此处需要关闭自动上传 不需要配置action参数 只需要做前端的本地预览图片即可 无需在提交之前上传图片 -->
        <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" :on-change="onSelectFile">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor ref="editorRef" v-model:content="formModel.content" content-type="html"
            theme="snow"></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
